import {
  editProfileApi,
  getCodeApi,
  getUserInfoApi,
  getUserProfileApi,
  loginApi,
  uploadPhotoApi,
} from '@/api/user';
import { setToken } from '@/utils/storage';
import { AppDispatch } from '../index';
import { EditProfileType, UserAction } from '../reducer/user';

//短信请求
export const sendCodeAction = (mobile: string) => {
  return async () => {
    const res = await getCodeApi(mobile);
    console.log(res);
    // return res;
  };
};
//登录请求
export const loginAction = (data: { mobile: string; code: string }) => {
  //异步调用action时，需要传递一个dispatch,在里面再调用，将请求结果传递给reducer
  return async (dispatch: AppDispatch) => {
    const res = await loginApi(data);
    console.log(res);
    dispatch({ type: 'user/login', payload: res.data });
    //将token保存到本地
    setToken(res.data);
  };
};
//获取自己信息请求（个人中心）
export const userInfoAction = () => {
  return async (dispatch: AppDispatch) => {
    const res = await getUserInfoApi();
    console.log(res);
    dispatch({ type: 'user/userInfo', payload: res.data });
  };
};

//获取个人资料
export const profileAction = () => {
  return async (dispatch: AppDispatch) => {
    const res = await getUserProfileApi();
    console.log(res);
    dispatch({ type: 'user/profile', payload: res.data });
  };
};
//编辑个人资料
export const editProfileAction = (data: EditProfileType) => {
  return async (dispatch: AppDispatch) => {
    const res = await editProfileApi(data);
    console.log(res);
  };
};
//上传头像
export const uploadPhotoAction = (data: FormData) => {
  return async (dispatch: AppDispatch) => {
    const res = await uploadPhotoApi(data);
    dispatch({ type: 'user/photo', payload: res.data.photo });
  };
};
//清理token
export const clearTokenAction = (): UserAction => {
  return { type: 'user/clearToken' };
};
